package com.leyou.user.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.leyou.auth.dto.UserDetail;
import com.leyou.auth.utils.JwtUtils;
import com.leyou.common.exception.LyException;
import com.leyou.common.utils.RegexUtils;
import com.leyou.user.dto.UserDTO;
import com.leyou.user.entity.User;
import com.leyou.user.mapper.UserMapper;
import com.leyou.user.service.UserService;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @description:
 * @author: YHL
 * @time: 2021/3/1 19:11
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    @Override
    public Boolean checkUserDate(String data, Integer type){
//       检查data数据是否为空
        if (StringUtils.isEmpty(data)){
             throw new LyException(400,"查询参数错误");
        }
        String colName =null;
        switch (type){
            case 1:colName ="username";
            break;
            case 2:
                if (!RegexUtils.isPhone(data)){
                    throw new LyException(400,"查询参数有误");
                }
                colName ="phone";
                break;
            default:
                throw new LyException(400,"查询参数有误");
        }
        //select count(id) from tb_user where username = #{leyou}
        return this.query().eq(colName,data).count()==1;
    }

    @Autowired
    private AmqpTemplate amqpTemplate;
    @Autowired
    private StringRedisTemplate redisTemplate;

    private final String KEY_PREFIX ="user:verify:code";
    @Override
    public void sendVerifyCode(String phone) {
        Map<String, String>msg =new HashMap<>();
        msg.put("phone",phone);
        String code = RandomStringUtils.randomNumeric(6);
        msg.put("code",code);
        //this.amqpTemplate.convertAndSend("dxjhj","verify",msg);
        this.redisTemplate.opsForValue().set(KEY_PREFIX+phone,code,5, TimeUnit.MINUTES);
    }


    @Autowired
    private BCryptPasswordEncoder passwordEncoder;

    @Override
    @Transactional
    public void createUser(User user, String code) {
        String key = KEY_PREFIX + user.getPhone();
        System.out.println("key = " + key);
        if (!redisTemplate.hasKey(key) || !code.equals(redisTemplate.opsForValue().get(key))) {

            throw new LyException(400,"验证码输入有误或已失效");
        }
        //保存已加密的密码
        user.setPassword( this.passwordEncoder.encode(user.getPassword()));
        this.save(user);
    }

    @Override
    public UserDTO queryUserByNameAndPass(String username, String password) {
        //select * from tb_user where username = #{username}
        User user = this.query()
                .eq("username", username)
                .one();
        //用户名不存在，或者密码校验失败，则抛异常
        if (null==user|| !this.passwordEncoder.matches(password,user.getPassword())){
            throw new LyException(400,"用户名或密码错误");
        }
        return new UserDTO(user);
    }
@Autowired
private JwtUtils jwtUtils;

}
